package com.item.prcatice;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Method {
    Scanner scanner = new Scanner(System.in);
    List<Student> list = new ArrayList<>();

    public void add() {
        System.out.println("请输入学生学号：");
        String id = scanner.next();
        if(isidExist(id)){
            System.out.println("你输入的学号已被占用，请重新输入");
            return;
        }
        System.out.println("请输入学生姓名：");
        String name = scanner.next();
        System.out.println("请输入学生年龄：");
        int age = scanner.nextInt();
        System.out.println("请输入学生居住地：");
        String address = scanner.next();
        Student st = new Student(id, name, age, address);
        list.add(st);
        System.out.println("添加成功");
    }
    public void delete(){
        System.out.println("请输入要删除学生的学号：");
        String id = scanner.next();
        int index = getIndex(id);
        if (index == -1){
            System.out.println("该信息不存在，请重新输入!");
        }else {
            list.remove(index);
            System.out.println("删除学生成功");
        }
    }
    public void update(){
        System.out.println("请输入要修改学生的学号：");
        String id = scanner.next();
        int index = getIndex(id);
        if (index == -1){
            System.out.println("该信息不存在，请重新输入!");
        }else {
            System.out.println("请输入学生新姓名：");
            String name = scanner.next();
            System.out.println("请输入学生新年龄：");
            int age = scanner.nextInt();
            System.out.println("请输入学生新居住地：");
            String address = scanner.next();
            list.set(index, new Student(id, name, age, address));
            System.out.println("修改学生成功");
        }
    }
    public void query(){
        System.out.println("学号\t姓名\t年龄\t\t居住地");
        for(Student student : list){
            System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getAge() + "岁\t" + student.getAddress());
        }
    }

    //获取索引
    private int getIndex(String id){
        for (int i = 0; i < list.size(); i++) {
            Student st = list.get(i);
            if (st.getId().equals(id)){
                return i;
            }
        }
        return -1;
    }
    private boolean isidExist(String id){
        return getIndex(id) != -1;
    }

}
